'use strict'

const http = require('http')
/*
.jpg .jpeg -> image/ipeg
.png -> image/png
.gif -> image/gif
.ico -> image/x-icon
.txt ->text/plain
.json -> text/json or application/json
.xml -> text/xml or application/xml
*/
let html = `
<!DOCTYPE html>
<html>
    <head>
        <title>FIRST HTTP</title>
    </head>
    <body>
        HELLO
    </body>
</html>
`

let routerTable = {
    '/': async (request, response) => {
        response.setHeader('content-type',
            'text/html;charset=utf-8')
        response.end(html)

    },
    '/test': async (request,response)=>{
        let status = parseInt(Math.random() * 200)+199
        response.statusCode = status
        response.end('test end')
    },
    '/data': async (resquest, response) => {
        let bufferList = []
        let bufferLength = 0
        request.on('data', chunk => {
            bufferLength += chunk.length
            bufferList.push(chunk)
        })
        let bodyData = null;
        request.on('end', () => {
            if (bufferList.length > 0) {
                bodyData = Buffer.concat(bufferList, bufferLength)
                bufferList = []
            }
            if (bodyData) {
                response.end(bodyData)
            } else {
                response.end()
            }
        })
    
    }
}

http.createServer((request, response) => {


 
    // console.log(request);
    // response.end('ok')

    //解析
    // response.setHeader('content-type',
    // 'text/html;charset=utf-8')
    //纯文本显示
    // response.setHeader('content-type',
    // 'text/plain;charset=utf-8')
    // response.end(html);


    if(!routerTable[ request.url ]){
        response.statusCode = 404
        response.end('page not found')
        return
    }
    routerTable[ request.url ](request,response)
})
    .listen(3456)